package edu.zjut.hjg.saas.biz.dao.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;

import edu.zjut.hjg.saas.biz.dao.ConsumptionDao;
import edu.zjut.hjg.saas.biz.model.Consumption;
import edu.zjut.hjg.saas.biz.support.Paginated;

public class ConsumptionDaoImpl extends SqlMapClientDaoSupport implements ConsumptionDao {

    @Override
    public Integer create(Consumption consumption) {
        return (Integer) getSqlMapClientTemplate().insert("consumption.create", consumption);
    }

    @SuppressWarnings("unchecked")
    @Override
    public Paginated<Consumption> listByTenantId(Integer tenantId, int pageSize, int page) {
        Map<String, Object> params = new HashMap<String, Object>();
        Integer totalSize = (Integer) getSqlMapClientTemplate().queryForObject(
                "consumption.countByTenantId", tenantId);
        int start = pageSize * (page - 1);
        if (start > totalSize) {
            start = (totalSize / pageSize) * pageSize;
        }
        params.put("tenantId", tenantId);
        params.put("pageSize", pageSize);
        params.put("start", start);
        List<Consumption> list = getSqlMapClientTemplate().queryForList(
                "consumption.listByTenantId", params);
        Paginated<Consumption> paginated = new Paginated<Consumption>();
        paginated.setValues(list);
        paginated.setPageSize(pageSize);
        paginated.setStart(start);
        paginated.setTotalSize(totalSize);
        return paginated;
    }

    @SuppressWarnings("unchecked")
    @Override
    public Paginated<Consumption> listByDateRang(Date fromDate, Date toDate, int pageSize, int page) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("fromDate", fromDate);
        params.put("toDate", toDate);
        Integer totalSize = (Integer) getSqlMapClientTemplate().queryForObject(
                "consumption.countByDateRang", params);
        int start = pageSize * (page - 1);
        if (start > totalSize) {
            start = (totalSize / pageSize) * pageSize;
        }
        params.put("pageSize", pageSize);
        params.put("start", start);
        List<Consumption> list = getSqlMapClientTemplate().queryForList(
                "consumption.listByDateRang", params);
        Paginated<Consumption> paginated = new Paginated<Consumption>();
        paginated.setValues(list);
        paginated.setPageSize(pageSize);
        paginated.setStart(start);
        paginated.setTotalSize(totalSize);
        return paginated;
    }
}
